import {
	AMapWX
} from '../utils/amap-wx.130.js';

// 创建 AMapWX 实例
const amap = new AMapWX({
	key: '86636e06e3f9dc05adbd0998ca37a8e4'
});

//  获取本地地址
export function getRegeoData() {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN || APP-PLUS
		amap.getRegeo({
			success: (data) => {
				const code = data[0].regeocodeData.addressComponent.adcode;
				const streetName = data[0].regeocodeData.addressComponent.township;
				const newData = {
					code: code,
					streetName: streetName
				};
				resolve(newData);
			},
			fail: (error) => {
				// 如果用户不肯给与定位权限 就默认返回这个地址 作废
				resolve({
					code: '441900',
					streetName: '大岭山镇'
				});
			}
		});
		// #endif
		// #ifndef MP-WEIXIN || APP-PLUS
		window._AMapSecurityConfig = {
			securityJsCode: "bf9f06e18b5e7dd1eab183695eb54615",
		};
		var url = "https://webapi.amap.com/maps?v=2.0&key=e315e9dfe5e6231a5a1fa0fddf75254d";
		var jsapi = document.createElement("script");
		jsapi.charset = "utf-8";
		jsapi.src = url;
		document.head.appendChild(jsapi);
		setTimeout(() => {
			AMap.plugin('AMap.Geolocation', function() {
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true,
					timeout: 5000,
					convert: true,
				})
				geolocation.getCurrentPosition((status, result) => {
					console.log(status, result);
					if (status == 'complete') {
						resolve(result)
					} else {
						resolve({
							code: '441900',
							streetName: '大岭山镇'
						});
					}
				});
			})
		}, 500)
		// #endif
	});
}

// 封装获取用户定位的方法 暂时没用上
export function getUserLocation() {
	return new Promise((resolve, reject) => {
		wx.getLocation({
			type: 'gcj02', // 返回可以用于高德地图的经纬度
			success: (res) => {
				const location = `${res.longitude},${res.latitude}`;
				resolve(location);
			},
			fail: (error) => {
				console.error('获取用户定位失败', error);
				// 使用默认经纬度
				const defaultLocation = '116.720733,39.904417';
				resolve(defaultLocation);
			}
		});
	});

}